//
//  CityInfoViewController.swift
//  驻外机组
//
//  Created by 苏伟 on 16/2/26.
//  Copyright © 2016年 com.csair. All rights reserved.
//

import UIKit
import SwiftyJSON

private let kTableHeightHeader: CGFloat = 400
private let kTableToBeCutOff: CGFloat = 70

//测试相机调用
class CityInfoViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {

    //@IBOutlet weak var imageView: UIImageView!
 
    //@IBOutlet weak var temp: UILabel!
    
    
    @IBOutlet var bigHeaderImageView: UIImageView!
    @IBOutlet var newsTableView: UITableView!
    @IBOutlet var dateLabel: UILabel!
    
    var cityName = "北京"
    var weatherInfo = ""
    
    var tableHeaderView: UIView!
    var tableHeaderMaskToBeVisible: CAShapeLayer!
    var newsArray = [News]()
    var arrayCheckCellHasLoaded = [Bool]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = "http://apis.baidu.com/heweather/weather/free"
        let httpArg:String="city=" + Citypinyin(cityName)
        
        request(url, httpArg: httpArg)
        creatingSampleNews()
        stylingDateLabel()
        configureNewsTable()
        updatingTableHeaderView()
        
        self.arrayCheckCellHasLoaded = [Bool](count: self.newsArray.count, repeatedValue: false)
        
        // 自定义返回按钮
        let backButton = UIBarButtonItem(title: "く返回", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
        
        self.navigationController?.navigationItem.leftBarButtonItem = backButton
        //self.navigationItem.leftBarButtonItem = backButton
        
        // 弥补因为返回按钮被替换导致的边缘滑入手势失效的问题
        let gesture = UIPanGestureRecognizer(target: self, action: "goBack")
        self.view.addGestureRecognizer(gesture)
       
        //fromAlbum()
    }
    
    //获取对应城市的拼音字符串
    func Citypinyin(cityname : String)->String{
        switch cityname {
        case "北京":
        return "beijing"
    
        case "阿姆斯特丹":
        return "amsterdam"
    
        default:
        return "beijing"
        }
    }
    

    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    func creatingSampleNews() {
        let news1 = News(newsTitle: weatherInfo, newsCategory: "城市天气")
        let news2 = News(newsTitle: "当地风情", newsCategory: "民俗")
        let news3 = News(newsTitle: "南航大酒店", newsCategory: "酒店")
        let news4 = News(newsTitle: "Shares falls as Euro plunges", newsCategory: "其他资料")
        let news5 = News(newsTitle: "SpaceX failure shows that we need more commercial space travel", newsCategory: "Science")
        let news6 = News(newsTitle: "Mac Rumor: Apple installs finger print detector on MacBooks", newsCategory: "Technology")
        let news7 = News(newsTitle: "Eclipse mints release new Blackcurrent flavor", newsCategory: "World")
        let news8 = News(newsTitle: "Aetna and Humana close to multi-billion dollar deal", newsCategory: "Finance")
        
        //newsArray = [news1, news2, news3, news4, news5, news6, news7, news8]
        
        newsArray = [news1,news2,news3,news4]
        
    }
    
    func stylingDateLabel() {
        self.dateLabel.text = cityName
        self.dateLabel.font = UIFont(name: "HelveticaNeue", size: 30)
        self.dateLabel.textColor = UIColor.whiteColor()
    }
    
    //MARK: table
    func configureNewsTable() {
        self.bigHeaderImageView.image = UIImage(named: cityName)
        
        self.tableHeaderView = self.newsTableView.tableHeaderView!
        self.newsTableView.tableHeaderView = nil
        self.newsTableView.addSubview(self.tableHeaderView)
        self.newsTableView.sendSubviewToBack(self.tableHeaderView)
        
        self.newsTableView.contentInset = UIEdgeInsetsMake(kTableHeightHeader, 0, 0, 0)
        self.newsTableView.contentOffset = CGPoint(x: 0, y: -kTableHeightHeader)
        
    }
    
    func updatingTableHeaderView() {
        var newsHeaderTableRect = CGRect(x: 0, y: -kTableHeightHeader, width: self.view.frame.size.width, height: kTableHeightHeader)
        
        if self.newsTableView.contentOffset.y < -kTableHeightHeader {
            newsHeaderTableRect.size.height = -self.newsTableView.contentOffset.y
            newsHeaderTableRect.origin.y = self.newsTableView.contentOffset.y
            
        }
        
        self.tableHeaderView.frame = newsHeaderTableRect
        
        visiblePortionOfNewsTableHeader(newsHeaderTableRect: newsHeaderTableRect)
    }
    
    func visiblePortionOfNewsTableHeader(newsHeaderTableRect newsHeaderTableRect: CGRect) {
        self.tableHeaderMaskToBeVisible = CAShapeLayer()
        self.tableHeaderMaskToBeVisible.fillColor = UIColor.blackColor().CGColor
        self.tableHeaderView.layer.mask = self.tableHeaderMaskToBeVisible
        
        let trapeziumHeaderMask = UIBezierPath()
        trapeziumHeaderMask.moveToPoint(CGPointMake(0, 0))
        trapeziumHeaderMask.addLineToPoint(CGPointMake(newsHeaderTableRect.width, 0))
        trapeziumHeaderMask.addLineToPoint(CGPointMake(newsHeaderTableRect.width, newsHeaderTableRect.height))
        trapeziumHeaderMask.addLineToPoint(CGPointMake(0, newsHeaderTableRect.height - kTableToBeCutOff))
        self.tableHeaderMaskToBeVisible.path = trapeziumHeaderMask.CGPath
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newsArray.count
    }
    
    
    //cell初始化
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let newsItem = newsArray[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell") as! NewsTableViewCell
        cell.newsCategory.text = newsItem.newsCategory
        cell.newsTitle.text = newsItem.newsTitle
        
        if indexPath.row % 2 == 0 {
            cell.newsCategory.textColor = UIColor.orangeColor()
        } else {
            cell.newsCategory.textColor = UIColor.purpleColor()
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 90
    }
    
    
    //选中事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        
        var selectIndex = indexPath.row
        var detail = cell?.textLabel?.text
        
        SweetAlert().showAlert((cell as! NewsTableViewCell).newsCategory.text!, subTitle:(cell as! NewsTableViewCell).newsTitle.text!, style: AlertStyle.None)
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if self.arrayCheckCellHasLoaded[indexPath.row] == false {
            cell.alpha = 0
            
            UIView.animateWithDuration(1, animations: { () -> Void in
                cell.alpha = 1
            });
            self.arrayCheckCellHasLoaded[indexPath.row] = true
        }
    }
    
    //MARK: ScrollView
    //图片下拉伸缩效果
    func scrollViewDidScroll(scrollView: UIScrollView) {        
        updatingTableHeaderView()
    }
    
    
    //选取相册
    func fromAlbum(){
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            //设置是否允许编辑
            picker.allowsEditing = true
            //弹出控制器，显示界面
            self.presentViewController(picker, animated: true, completion: { () -> Void in
            })
        }else{
            print("读取相册错误")
        }
    }
    
    //照片选中后回调方法
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        //info对象
//        print(editingInfo)
//        //获取原图
//        imageView.image = image
//        //图片控制器退出
//        picker.dismissViewControllerAnimated(true) { () -> Void in
//        }
//        
//    }
    
    //打开摄像头
    func openCamera(){
        //摄像头测试
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
            //图片控制器
            let picker = UIImagePickerController()
            //设置代理
            picker.delegate = self
            //设置来源
            picker.sourceType = UIImagePickerControllerSourceType.Camera
            //允许编辑
            picker.allowsEditing = true
            //开启闪光灯
            //picker.cameraFlashMode = UIImagePickerControllerCameraFlashMode.On
            //打开相机
            self.presentViewController(picker, animated: true, completion: { () -> Void in
                
            })
        }else{
            print("找不到相机")
        }
    }
    
    
    //打开第三方APP
    func openAPP(){
        //今日头条是否安装
                if(UIApplication.sharedApplication().canOpenURL(NSURL(string: "snssdk141://")!)){
                    print("安装了")
        
                }else{
                    print("未安装")
                    //调用电话
                    UIApplication.sharedApplication().openURL(NSURL(string: "weixin://dl/scan")!)
                }
        
        //打开指定app
        UIApplication.sharedApplication().openURL(NSURL(string: "mqq://")!)
    }
    
    //返回逻辑
    func goBack(){
        self.navigationController?.popViewControllerAnimated(true)
        Common.rootViewController.mainTabBarController.tabBar.hidden = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func request(httpUrl: String, httpArg: String) {
        let req = NSMutableURLRequest(URL: NSURL(string: httpUrl + "?" + httpArg)!)
        req.timeoutInterval = 6
        req.addValue("9edac835f376cb64772fbcd764fcc94b", forHTTPHeaderField: "apikey")
        //响应对象
        var response:NSURLResponse?
        
        do{
            //发出请求
            let received:NSData? = try NSURLConnection.sendSynchronousRequest(req,
                returningResponse: &response)

            
            let json = JSON(data:received!)
            
            
            //当前体感温度
            if let tempNow = json["HeWeather data service 3.0"][0]["now"]["fl"].string{
                //print("-------" + city)
                weatherInfo += " 当前气温为:" + tempNow + "℃"
            }else{
                print(json["HeWeather data service 3.0"][0]["now"]["fl"].error)
            }
            //最高温度
            if let maxTemp = json["HeWeather data service 3.0"][0]["daily_forecast"][0]["tmp"]["max"].string{
                //print("-------" + city)
                weatherInfo += " 最高气温为:" + maxTemp
            }else{
                print(json["HeWeather data service 3.0"][0]["daily_forecast"][0]["tmp"]["max"].error)
            }
            //最低温度
            if let minTemp = json["HeWeather data service 3.0"][0]["daily_forecast"][0]["tmp"]["min"].string{
                //print("-------" + city)
                weatherInfo += " 最低气温为:" + minTemp
            }else{
                print(json["HeWeather data service 3.0"][0]["daily_forecast"][0]["tmp"]["min"].error)
            }
            
        }catch let error as NSError{
            //打印错误消息
            print(error.code)
            print(error.description)
        }
    }
}
